package org.jeecg.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Encoder;
import org.jeecg.common.constant.CommonConstant;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


/**
 * @Auther: 养猪厂长L先生
 * @Date: 2022/5/13 14:13
 * @Description: 获取小程序二维码
 */
@Component
public class WeChatQrCodeUtils {
    /**
     *
     * @Description TODO
     * @date 2022/5/13 17:20
     * @param accessToken_URL 请求接口路径
     * @param appId 小程序appId
     * @param appSecret 小程序密钥
     * @return String 生成的Token值
     */

    public static String getAccessToken(String accessToken_URL, String appId, String appSecret,RedisUtil redisUtil) throws IOException {
        String accesstoken = null;
        accesstoken = (String)redisUtil.get(CommonConstant.PREFIX_WECHAT_MINI_ACCESS_TOKEN+appId);
        if(StringUtils.isEmpty(accesstoken)){
            String requestUrl = accessToken_URL.replace("APPID", appId).replace("APPSECRET", appSecret);
            URL url = new URL(requestUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            // 设置通用的请求属性
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 得到请求的输出流对象
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes("");
            out.flush();
            out.close();
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = null;
            if (requestUrl.contains("nlp"))
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
            else
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String result = "";
            String getLine;
            while ((getLine = in.readLine()) != null) {
                result += getLine;
            }
            in.close();
            JSONObject jsonObject = JSON.parseObject(result);
            accesstoken = jsonObject.getString("access_token");
            redisUtil.set(CommonConstant.PREFIX_WECHAT_MINI_ACCESS_TOKEN+appId,accesstoken);
            redisUtil.expire(CommonConstant.PREFIX_WECHAT_MINI_ACCESS_TOKEN+appId,CommonConstant.WECHAT_MINI_ACCESS_TOKEN_EXPIRE_TIME);

        }else{
        }
        return accesstoken;
    }

    /**
     *
     * @Description TODO
     * @date 2022/5/13 17:19
     * @param accessToken 通过getAccessToken方法获取
     * @param request_URL 生成二维码请求接口
     * @param page 跳转页面
     * @param scene 携带参数 格式为："aa=108&bb=2&cc=3"
     * @return String 图像名称
     */


    public static InputStream generateQrCode(String accessToken, String request_URL, String page, String scene) {

        try {
            //调用微信接口生成二维码
            URL url = new URL(request_URL + accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            //这就是你二维码里携带的参数 String型  名称不可变
            paramJson.put("scene", scene);
            //注意该接口传入的是page而不是path,这是设置扫描二维码后跳转的页面
            paramJson.put("page", page);
            paramJson.put("width", 200);
            paramJson.put("is_hyaline", false);
            paramJson.put("auto_color", true);
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();

            //开始获取二维码数据
            BufferedInputStream Qrdbis = new BufferedInputStream(httpURLConnection.getInputStream());
            DataInputStream dis = new DataInputStream(Qrdbis);
            return Qrdbis;
        } catch (Exception e) {
            e.printStackTrace();
        }
       return null ;

    }
}
